var SdsAsmt = {
    asmtInfo: null,//评估字典信息
    asmtScore: 0, // 分数
    asmtLevel: "", // 等级
    evalId: 0, // 评估id
    sdsAsmtData: {},
    layerIndex: -1
};
/**
 * 展示条目
 */
function loadAsmtItem(){
    var listHtml=""
    //初始化分值
    var score = SdsAsmt.asmtInfo.asmtItems[0].score;
    if (score == ""||score==null) {
        score = "0";
    }
    SdsAsmt.asmtScore = score;
    SdsAsmt.asmtLevel = judgeLevel(score);
    $('#asmtScore').text(score + '分');
    var clazz = returnLevelClass(SdsAsmt.asmtLevel);
    if(SdsAsmt.asmtLevel !=""){
        $('#asmtResult').text("("+SdsAsmt.asmtLevel+")").removeClass().addClass(clazz);
    }
    //动态生成评分表html
    var listHtml=listHtml+'<div>'
    var asmtItems = SdsAsmt.asmtInfo.asmtItems;
    SdsAsmt.evalId = SdsAsmt.asmtInfo.asmtItems[0].evalId;
    var IComb = SdsAsmt.asmtInfo.asmtItems[0].showStyle;//1 竖分；2横分；3横分独表
    var sheetCode=SdsAsmt.asmtInfo.asmtItems[0].sheetCode;
    var itemlen=asmtItems.length;
    var itemPWidth='200px';
    if (itemlen==1) itemPWidth='98%';  //唯一评分项  展开全部
    var listHtml=listHtml+'<div>'
    var itemhtml=""
    var HCount=0 //加载行div
    var itemCount=0 //默认列数
    for (var xind=0;xind<itemlen;xind++) {
        var xitem=asmtItems[xind];
        var itemid=xitem.itemId;
        var itemcode=xitem.itemCode;
        var itemdesc=xitem.itemDesc;
        var multiple=xitem.multipleChoice?true:false;
        var itemDtl=xitem.itemDtl.split("#");
        //从代码处理当前项目位置信息
        var xitemcode=itemcode.replace(sheetCode,"");
        var xitemcodeArr	= xitemcode.split('-');
        var xhcount			= xitemcodeArr[1];   //行位置
        var xvcount			= xitemcodeArr[2];	//列位置
        var xstyle			= xitemcodeArr[3];	//合并样式
        if (xhcount!=HCount) {
            itemCount=1 //默认一行一列
            if (HCount>0) {
                //给上一个div加上结束标签
                var itemhtml=itemhtml+'</div>'
            }
            if (IComb==3){
                var itemhtml=itemhtml+'<div class="item-h3" id="hdiv'+xhcount+'">'
            }else{
                var itemhtml=itemhtml+'<div class="item-h" id="hdiv'+xhcount+'">'
            }
            HCount=xhcount
            //新写入一行前，计算总列数
            for (var yind=xind+1;yind<itemlen;yind++) {
                var yitem=asmtItems[yind];
                var yitemcode=yitem.itemCode;
                var yitemcode=yitemcode.replace(sheetCode,"");
                var yitemcodeArr	= yitemcode.split('-');
                var yhcount			= yitemcodeArr[1];   //行位置
                if (yhcount!=xhcount) break;
                var yvcount			= yitemcodeArr[2];	//列位置
                if (yvcount>0) itemCount=yvcount;
            }

        }
        if (itemCount==0) continue;
        var itemDics = xitem.itemDics;
        var itemdicLen=itemDics.length;
        if (IComb==3) {
            //横分表构建
            //第一个评分项构建评分表头
            var titlehtml="",dichtml="";
            if (xind==0) {
                //计算列宽
                var colWidth=99/(itemdicLen+1)+"%";
                //补项目分类头
                var titlehtml=titlehtml+'<div class="dic-title" style="width:'+colWidth+'">'+"项目"+'</div>'
                var dichtml='<div data-multiple='+multiple+' id="'+itemid+'" ><div class="dic-title3" style="width:'+colWidth+'">'+itemdesc+'</div>'
                for (var dind=0;dind<itemdicLen;dind++) {
                    var xitemdic=itemDics[dind];
                    var EDRowID	= xitemdic.dicId;
                    var EDCode	= xitemdic.dicCode;
                    var EDDesc	= xitemdic.dicDesc;
                    var EDScore	= xitemdic.dicScore;
                    var EDType	= xitemdic.type;
                    var EDExp	= xitemdic.formula;
                    var EDGroup	= xitemdic.mutexFlag;
                    var EDLink	= xitemdic.relationFlag;
                    var titlehtml=titlehtml+'<div class="dic-title" style="width:'+colWidth+'">'+EDScore+'</div>'
                    for (var i = 0; i < itemDtl.length; i++) {
                        var choiItem = itemDtl[i];
                        if (EDRowID == choiItem) {
                            var dichtml=dichtml+'<div id='+EDRowID+' class="dic-desc dic-desc-selected" data-calc="'+EDExp+'"  data-score="'+EDScore+'" data-link="'+EDLink+'" data-group="'+EDGroup+'" style="width:'+colWidth+';">'+EDDesc+'</div>'
                            break;
                        } else {
                            var dichtml=dichtml+'<div id='+EDRowID+' class="dic-desc" data-calc="'+EDExp+'"  data-score="'+EDScore+'" data-link="'+EDLink+'" data-group="'+EDGroup+'" style="width:'+colWidth+';">'+EDDesc+'</div>'
                        }
                    }
                }
                var dichtml=dichtml+'</div>'
                titlehtml='<div style="margin-top:10px;" class="item-h3" id="hdiv'+0+'">'+titlehtml+'</div>'
                dichtml='<div class="item-h3" id="hdiv'+1+'">'+dichtml+'</div>'
                itemhtml=titlehtml+dichtml
            }else {
                var dichtml='<div data-multiple='+multiple+' id="'+itemid+'" ><div class="dic-title3" id="'+itemid+'" style="width:'+colWidth+'">'+itemdesc+'</div>'
                for (var dind=0;dind<itemdicLen;dind++) {
                    var xitemdic=itemDics[dind];
                    var EDRowID	= xitemdic.dicId;
                    var EDCode	= xitemdic.dicCode;
                    var EDDesc	= xitemdic.dicDesc;
                    var EDScore	= xitemdic.dicScore;
                    var EDType	= xitemdic.type;
                    var EDExp	= xitemdic.formula;
                    var EDGroup	= xitemdic.mutexFlag;
                    var EDLink	= xitemdic.relationFlag;
                    for (var i = 0; i < itemDtl.length; i++) {
                        var choiItem = itemDtl[i];
                        if (EDCode == choiItem) {
                            var dichtml=dichtml+'<div id='+EDRowID+' class="dic-desc dic-desc-selected" data-calc="'+EDExp+'"  data-score="'+EDScore+'" data-link="'+EDLink+'" data-group="'+EDGroup+'" style="width:'+colWidth+';">'+EDDesc+'</div>'
                            break;
                        } else {
                            var dichtml=dichtml+'<div id='+EDRowID+' class="dic-desc" data-calc="'+EDExp+'"  data-score="'+EDScore+'" data-link="'+EDLink+'" data-group="'+EDGroup+'" style="width:'+colWidth+';">'+EDDesc+'</div>'
                        }
                    }
                }
                var dichtml=dichtml+'</div>'
                itemhtml=itemhtml+dichtml
            }
        }else if(IComb==2){
            var itemWidth=99/itemCount+"%"
            var itemhtml=itemhtml+'<div class="item-panel" id="'+itemid+'" data-multiple='+multiple+' style="width:'+itemWidth+';">'
            var itemhtml=itemhtml+'<div class="dic-title">'+itemdesc+'</div>'
            var itemdicLen=itemDics.length;
            for (var dind=0;dind<itemdicLen;dind++) {
                var xitemdic=itemDics[dind];
                var EDRowID	= xitemdic.dicId;
                var EDCode	= xitemdic.dicCode;
                var EDDesc	= xitemdic.dicDesc;
                var EDScore	= xitemdic.dicScore;
                var EDType	= xitemdic.type;
                var EDExp	= xitemdic.formula;
                var EDGroup	= xitemdic.mutexFlag;
                var EDLink	= xitemdic.relationFlag;
                var EDDesc=EDDesc.replace(/\r\n/g,"<br>");
                for (var i = 0; i < itemDtl.length; i++) {
                    var choiItem = itemDtl[i];
                    if (EDCode == choiItem) {
                        var itemhtml=itemhtml+'<div id='+EDRowID+' class="dic-desc dic-desc-selected" data-calc="'+EDExp+'"  data-score="'+EDScore+'" data-link="'+EDLink+'" data-group="'+EDGroup+'" style="float:left;width:98%;height:100%;">'+EDDesc+'</div>'
                        break;
                    } else {
                        var itemhtml=itemhtml+'<div id='+EDRowID+' class="dic-desc" data-calc=\"'+EDExp+'\"  data-score=\"'+EDScore+'\" data-link=\"'+EDLink+'\" data-group=\"'+EDGroup+'\" style="float:left;width:98%;height:100%;">'+EDDesc+'</div>'
                    }
                }
                var itemhtml=itemhtml+'<div style="clear:both"></div>'
            }
            var itemhtml=itemhtml+'</div>'
        }else{
            var itemWidth=99/itemCount+"%"
            var itemhtml=itemhtml+'<div class="item-panel" id="'+itemid+'" data-multiple='+multiple+' style="width:'+itemWidth+';">'
            var itemhtml=itemhtml+'<div class="dic-title">'+itemdesc+'</div>'
            var itemdicLen=itemDics.length;
            for (var dind=0;dind<itemdicLen;dind++) {
                var xitemdic=itemDics[dind];
                var EDRowID	= xitemdic.dicId;
                var EDCode	= xitemdic.dicCode;
                var EDDesc	= xitemdic.dicDesc;
                var EDScore	= xitemdic.dicScore;
                var EDType	= xitemdic.type;
                var EDExp	= xitemdic.formula;
                var EDGroup	= xitemdic.mutexFlag;
                var EDLink	= xitemdic.relationFlag;
                var EDDesc=EDDesc.replace(/\r\n/g,"<br>");
                // var EDDesc=EDDesc.replace(/\s/g,"<br>");
                /*
                <input id="huodongdu" placeholder="8度=1分，最高18分">
                <div>每5度外翻<input id="waifandu">度</div>
                */
                var itemhtml=itemhtml+'<div class="dic-score">'+EDScore+'</div>'
                if (EDType=="input") {
                    if (EDExp=="") {
                        var itemhtml=itemhtml+'<div style="float:left;"><input id='+EDRowID+' class="dic-input" placeholder='+EDDesc+'></div>'
                    }else{
                        var itemhtml=itemhtml+'<div style="float:left;">'+EDDesc+'<input id='+EDRowID+' data-calc=\"'+EDExp+'\" class="dic-input"></div>'
                    }
                }else{
                    var innerhtml="";
                    for (var i = 0; i < itemDtl.length; i++) {
                        var choiItem = itemDtl[i];

                        if (EDCode == choiItem) {
                            innerhtml=innerhtml+'<div id='+EDRowID+' class="dic-desc dic-desc-selected" data-calc=\"'+EDExp+'\"  data-score=\"'+EDScore+'\" data-link=\"'+EDLink+'\" data-group=\"'+EDGroup+'\" >'+EDDesc+'</div>'
                            break;
                        }
                        // else {
                        //     var itemhtml=itemhtml+'<div id='+EDRowID+' class="dic-desc" data-calc=\"'+EDExp+'\"  data-score=\"'+EDScore+'\" data-link=\"'+EDLink+'\" data-group=\"'+EDGroup+'\" >'+EDDesc+'</div>'
                        //
                        // }
                    }
                    if(innerhtml ==""){
                        innerhtml=innerhtml+'<div id='+EDRowID+' class="dic-desc" data-calc=\"'+EDExp+'\"  data-score=\"'+EDScore+'\" data-link=\"'+EDLink+'\" data-group=\"'+EDGroup+'\" >'+EDDesc+'</div>';
                    }
                }
                var itemhtml=itemhtml + innerhtml+'<div style="clear:both"></div>'
            }
            var itemhtml=itemhtml+'</div>'
        }

    }
    var listHtml=listHtml+itemhtml
    var listHtml=listHtml+'</div>'  //最后一个行div结束
    var listHtml=listHtml+'</div></div>'
    $(".evalItemBlock").prepend(listHtml);
    $.parser.parse(".evalItemBlock");  //解析radio
    // $('#ValDic').html(listHtml)
    // $('#winVal').dialog({title:aSheetTitle})
    // $HUI.dialog('#winVal').open();
    // $.parser.parse('#ValDic');
    //选中div时 计算分值
    $('.dic-desc').on('click',function(){

        //如果容器标记为单选，则先移除所有选中，再选中当前
        if ($(this).parent().attr('data-multiple')=='false') {
            if ($(this).hasClass('dic-desc-selected')) {
                $(this).parent().find('.dic-desc-selected').removeClass('dic-desc-selected');
            }else {
                $(this).parent().find('.dic-desc-selected').removeClass('dic-desc-selected');
                $(this).addClass('dic-desc-selected');
            }
        }else{
            //如果容器标记为多选，则当前切换选中状态
            $(this).toggleClass('dic-desc-selected');
        }
        //搜索父容器下所有互斥项，取消所有互斥项的选中状态
        if ($(this).hasClass('dic-desc-selected')) {
            var selectedText=$(this).text();
            var groupinfo=$(this).attr('data-group');
            var linkinfo=$(this).attr('data-link');
            if (groupinfo) {
                //清除同分组信息下的其他选项
                $('div[data-group='+groupinfo+']').each(function(i, v){
                    if (selectedText!=$(this).text()) {
                        $(this).removeClass('dic-desc-selected');
                    }
                })
            }
            if (linkinfo) {
                //选中相关联的其他选项
                $('div').find('.dic-desc-selected').removeClass('dic-desc-selected');
                $('div[data-link='+linkinfo+']').each(function(i, v){
                    $(this).addClass('dic-desc-selected');
                })
            }
        }
        calVal(sheetCode);
    })
    //输入框计算到总分值
    $('.dic-input').on('input',function(){
        calVal(sheetCode);
    })

    var levelArr = SdsAsmt.asmtInfo.levelRange;
    var levelInfo = "";
    for(var i=0;i<levelArr.length;i++){
        var minValue = parseInt(levelArr[i].minVal);
        var maxValue = parseInt(levelArr[i].maxVal);
        var levelDesc = levelArr[i].level;
        levelInfo += levelDesc + ":" + minValue + "-" + maxValue + "/";
    }
    $('#asmtLevelInfo').text(levelInfo);
}

/**
 * 加载评估字典信息
 */
function loadAsmtInfo(){
    var param = {};
    var ajax = new $ax("/sds/sdsqcformshow/getAsmtInfo", function (res) {
        SdsAsmt.asmtInfo = res;
        loadAsmtItem();
    }, function () {
    });
    param.asmtId = $("#asmtId").val();
    param.patientId = $("#patientId").val();
    ajax.set(param);
    ajax.start();
}
/**
 * 上报自动评估信息后端保存
 */
function loadAIInfo(){
    var param = {};
    var ajax = new $ax("/sds/sdsqcformshow/saveAIAsmtInfo", function () {
    }, function () {
    });
    param.patientId = $("#patientId").val();
    param.entityId = $("#entityId").val();
    param.asmtId = $("#asmtId").val();
    param.fitemId = $("#fitemId").val();
    ajax.set(param);
    ajax.start();
}
/**
 * 上报自动评估信息后端返回
 */
function getAutoNodeInfo(){
    // $('span.auto').remove();
    //
    // $('div').find('.dic-desc-selected').removeClass('dic-desc-selected');
    var ajax = new $ax("/sds/sdsqcformshow/getAIAsmtInfo", function (data) {
        var l = data.length;
        var scoreT = 0;
        for (var i = 0; i < data.length; i++) {
            var itemId = data[i].assessmentEntryId;
            $("#"+itemId).addClass("dic-desc-selected");
            var x = "<span id="+data[i].id+" class='auto' style='position: absolute;margin-left: 100px;'>A</span>";
            document.getElementById(itemId).innerHTML += x;
            getItemKeyFrom("", data[i].id);
            //获取得分
            var score = data[i].score;
            scoreT+=score;
        }
        $('#asmtScore').text(scoreT);
        SdsAsmt.asmtScore = scoreT;
        //获取死亡率
        var level = judgeLevel(scoreT);
        var clazz = returnLevelClass(level);
        // $('#asmtScore').text(SdsAsmt.asmtScore).removeClass().addClass(clazz);
        if(level !=""){
            $('#asmtResult').text("("+level+")").removeClass().addClass(clazz);
        }
    }, function (data) {
    });
    var params = {};
    params.patientId = $("#patientId").val();
    params.entityId = $("#entityId").val();
    params.asmtId = $("#asmtId").val();
    ajax.set(params);
    ajax.start();
}
function getItemKeyFrom(evalItemId, evalHisId){
    var param = {};
    var ajax = new $ax("/api/sdstool/getItemKeyFrom", function (data) {
        if (data != null) {
            var titleStr = (data) + "<br>";
            var indexItem = null;

            if (evalItemId != ""){
                $("#" + evalItemId).hover(function () {
                    indexItem = layer.tips(titleStr, $("#" + evalItemId), {
                        tips: 3,
                        area: ['250px', 'auto'],
                        time: 5000
                    });
                }, function () {
                    layer.close(indexItem);
                });
            }

            if (evalHisId != ""){
                $("#" + evalHisId).hover(function () {
                    indexItem = layer.tips(titleStr, $("#" + evalHisId), {
                        tips: 3,
                        area: ['250px', 'auto'],
                        time: 5000
                    });
                }, function () {
                    layer.close(indexItem);
                });
            }

        }
    }, function (data) {
    });
    param.evalItemId = evalItemId;
    param.evalHisId = evalHisId;
    ajax.set(param);
    ajax.start();
}

/**
 * 判断不同类型量表级别描述
 * @param score
 * @returns judgeRiskLevel
 */
function judgeLevel(score){
    var levelDesc = "";
    score = parseInt(score);
    var dicLevelInfo = SdsAsmt.asmtInfo.levelRange;
    for(var i=0;i<dicLevelInfo.length;i++){
        var minValue = parseInt(dicLevelInfo[i].minVal);
        var maxValue = parseInt(dicLevelInfo[i].maxVal);
        if(score>=minValue&&score<=maxValue){
            levelDesc = dicLevelInfo[i].level;
        }
    }
    return levelDesc;
}

/**
 * 计算分数和结果  每次选中/填写评估表，计算当前所得分值
 */
function calVal(sheetCode){
    //初始化评估得分、值、评分字典
    var tscore=0,tval="",selectdicstr="";
    // obj.ScoreArr[obj.EQCItemCode]=""
    $('div').find('.dic-desc-selected').each(function(i, v){
        var xscore=$(this).attr('data-score');
        selectdicstr=selectdicstr+"^"+$(this).attr('id');
        if (!isNaN(parseFloat(xscore))) {
            //分值评定，分值相加
            tscore=tscore+parseFloat(xscore);
        }else {
            //等级评估，直接显示等级描述
            tscore=xscore
            //如果有计算表达式，按照计算公式进行转换
            texp=$(this).attr('data-calc');
            if (texp) {
                texp.replace('this',xscore);
                tval=eval('texp');
            }
        }
    })

    $('.dic-input').each(function(i, v){
        texp=$(this).attr('data-calc')
        xscore=$(this).val()
        if (xscore!="") {
            if (texp) {
                texp=texp.replace('this',xscore)
                //计算表达式结果值 保留2位小数
                xscore=eval(texp).toFixed(2)
            }
            tscore=tscore+Number(xscore)
            selectdicstr=selectdicstr+"^"+$(this).attr('id')+"`"+$(this).val()
        }
    })
    if(!isNaN(tscore)) {
        $('#asmtScore').text(Number(tscore.toFixed(2)));
    }else{
        $('#asmtScore').text(tscore);
    }
    if (tval) {
        $('#asmtScore').val(tval)
    }
    // obj.ScoreArr[obj.EQCItemCode]=tscore+"#"+selectdicstr

    SdsAsmt.asmtLevel = judgeLevel(tscore);
    SdsAsmt.asmtScore = tscore;
    var clazz = returnLevelClass(SdsAsmt.asmtLevel);
    // $('#asmtScore').text(SdsAsmt.asmtScore).removeClass().addClass(clazz);
    if(SdsAsmt.asmtLevel !=""){
        $('#asmtResult').text("("+SdsAsmt.asmtLevel+")").removeClass().addClass(clazz);
    }
}
/**
 * 获取对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
SdsAsmt.get = function (key, type) {
    var res = "";
    switch (type) {
        case "checkbox":
            $("input[type='checkbox'][name=" + key + "]:checked").each(function () {
                //  选中复选框中的值
                res += $(this).val() + ",";
            });
            res = res.substring(0, res.length - 1)
            break;
        case "radio":
            var obj = $("input[type='radio'][name=" + key + "]:checked");
            res = obj.val();
            break;
        default:
            res = $("input[name=" + key + "]").val();
            break;
    }
    return res;
};

/**
 * 收集选择项
 */
SdsAsmt.collectData = function () {
    $(".dic-desc-selected").each(function () {
        SdsAsmt.sdsAsmtData[$(this)[0].id] = $(this)[0].id;
    });
};

/**
 * 保存禁忌症
 */
SdsAsmt.save = function () {
    // 保存时，计算分数
    // calcScore();
    // 收集数据
    this.collectData();
    //提交信息
    var ajax = new $ax("/sds/sdsqcformshow/saveAsmtInfo", function (data) {
        layer.msg("保存成功!");
        var postData = {};
        postData.type = "save";
        postData.score = SdsAsmt.asmtScore;
        postData.level = SdsAsmt.asmtLevel;
        parent.postMessage(postData,"*");
    }, function (data) {
        layer.error("保存失败!");
    });
    var params = {};
    params.patientId = $('#patientId').val();
    params.asmtId = $('#asmtId').val();
    params.evalId = SdsAsmt.evalId;
    params.sdsAsmtData = JSON.stringify(this.sdsAsmtData);
    params.score = SdsAsmt.asmtScore;
    params.level = SdsAsmt.asmtLevel;
    ajax.set(params);
    ajax.start();
}

/**
 * 关闭弹窗
 */
SdsAsmt.close = function () {
    parent.postMessage("close","*");
}

/**
 * 返回等级信息Class 颜色区分
 */
function returnLevelClass(levelName) {
    var clazz = "";
    switch (levelName) {
        case "极低危":
            clazz = "vlowRisk";
            break;
        case "低危":
        case "低度可能":
            clazz = "lowRisk";
            break;
        case "中危":
        case "中度可能":
            clazz = "mhighRisk";
            break;
        case "高危":
        case "高度可能":
            clazz = "highRisk";
            break;
        case "极高危":
            clazz = "vhighRisk";
            break;
        default:
            clazz = "vlowRisk";
            break;
    }
    return clazz;
}

$(function () {
    //获取评估字典信息
    loadAsmtInfo();
    //上报自动评估信息后端保存
    loadAIInfo();
    //获取自动评估信息
    getAutoNodeInfo();
});